import sys
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

def load_image(image_path):
    """加载图像并转换为灰度图"""
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return image_rgb, gray_image

def plot_histogram(image, title="图像直方图", save_path=None):
    """绘制图像直方图"""
    plt.figure(figsize=(10, 6))
    hist = cv2.calcHist([image], [0], None, [256], [0, 256])
    plt.plot(hist, color='black')
    plt.xlim([0, 256])
    plt.title(title)
    plt.xlabel('像素强度')
    plt.ylabel('像素数量')
    plt.grid(True)
    if save_path:
        plt.savefig(save_path)
    plt.show()

def evaluate_image_quality(image):
    """评价图像质量（基于直方图分析）"""
    # 计算直方图
    hist = cv2.calcHist([image], [0], None, [256], [0, 256])
    hist = hist.flatten() / hist.sum()
    # 计算质量指标
    mean_value = np.mean(image)  
    std_dev = np.std(image)      
    # 计算熵（信息量）
    epsilon = 1e-10
    entropy = -np.sum(hist * np.log2(hist + epsilon))
    # 动态范围
    dynamic_range = np.max(image) - np.min(image)
    # 直方图均匀性
    uniformity = np.sum(np.square(hist))
    return {
        "平均灰度值": mean_value,
        "标准差（对比度）": std_dev,
        "熵（信息量）": entropy,
        "动态范围": dynamic_range,
        "直方图均匀性": uniformity
    }
def enhance_image(image):
    """图像增强（直方图均衡化）"""
    enhanced_image = cv2.equalizeHist(image)
    return enhanced_image
def segment_image(image, threshold_value=127):
    """图像分割（阈值法）"""
    _, segmented_image = cv2.threshold(image, threshold_value, 255, cv2.THRESH_BINARY)
    return segmented_image
def compress_image(image_path, output_path, quality=85):
    """图像压缩"""
    # 使用PIL进行压缩
    img = Image.open(image_path)
    img.save(output_path, quality=quality, optimize=True)
    
    # 计算压缩比
    original_size = os.path.getsize(image_path)
    compressed_size = os.path.getsize(output_path)
    
    return original_size, compressed_size

def display_images(images, titles, figsize=(15, 10)):
    """显示多个图像"""
    n = len(images)
    plt.figure(figsize=figsize)
    
    for i in range(n):
        plt.subplot(1, n, i+1)
        if len(images[i].shape) == 2:  
            plt.imshow(images[i], cmap='gray')
        else:  # 彩色图
            plt.imshow(images[i])
        plt.title(titles[i])
        plt.axis('off')
    
    plt.tight_layout()
    plt.show()

def main():
    # 图像路径
    image_path = r"H:\vscode\python\something-1\IMG_0634.JPG"
    output_dir = r"H:\vscode\python\something-1\output"
    os.makedirs(output_dir, exist_ok=True)
    original_image, gray_image = load_image(image_path)
    display_images([original_image, gray_image], ["原始图像", "灰度图像"])
    plot_histogram(gray_image, "灰度图像直方图", os.path.join(output_dir, "histogram.png"))
    quality_metrics = evaluate_image_quality(gray_image)
    for metric, value in quality_metrics.items():
        print(f"{metric}: {value:.4f}")
    enhanced_image = enhance_image(gray_image)
    plot_histogram(enhanced_image, "增强后图像直方图", os.path.join(output_dir, "enhanced_histogram.png"))
    display_images([gray_image, enhanced_image], ["原始灰度图像", "直方图均衡化后"])

    otsu_threshold, segmented_image_otsu = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    segmented_image_fixed = segment_image(gray_image, 127)
    display_images([gray_image, segmented_image_otsu, segmented_image_fixed], 
                  ["原始灰度图像", f"Otsu阈值分割 (阈值={otsu_threshold:.1f})", "固定阈值分割 (阈值=127)"])
    
 
    compressed_path = os.path.join(output_dir, "compressed.jpg")
    original_size, compressed_size = compress_image(image_path, compressed_path, quality=75)
    compression_ratio = original_size / compressed_size
    print(f"原始图像大小: {original_size / 1024:.2f} KB")
    print(f"压缩后图像大小: {compressed_size / 1024:.2f} KB")
    print(f"压缩比: {compression_ratio:.2f}")
    
    cv2.imwrite(os.path.join(output_dir, "enhanced.jpg"), enhanced_image)
    cv2.imwrite(os.path.join(output_dir, "segmented_otsu.jpg"), segmented_image_otsu)
    cv2.imwrite(os.path.join(output_dir, "segmented_fixed.jpg"), segmented_image_fixed)
    
    print("处理完成！所有结果已保存到输出目录。")

if __name__ == "__main__":
    main()
